package com.maxh.interceptor;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.maxh.annotation.*;
import com.maxh.pojo.Admin;
import com.maxh.pojo.Teacher;
import com.maxh.service.LoginService;
import com.maxh.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.maxh.pojo.User;


/**
 * @author jinbin
 * @date 2018-07-08 20:41
 */
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    LoginService loginService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        Admin admin=null;
        Teacher teacher = null;
        User user = null;
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
//            System.out.println("如果不是映射到方法直接通过");
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
//            System.out.println("检查是否有passtoken注释，有则跳过认证");
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要讲师权限的注解
        if (method.isAnnotationPresent(TeacherLoginToken.class)) {
//            System.out.println("检查有没有需要用户权限的注解");
            TeacherLoginToken teacherLoginToken = method.getAnnotation(TeacherLoginToken.class);
            if (teacherLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new MyException(StatusCode.USER_NOT_EXIST, "无token，请重新登录");
                }
                // 获取 token 中的 user id
                String teacherId;
                try {
                    teacherId = JWT.decode(token).getAudience().get(0);
                    System.out.println(teacherId);
                    if(teacherId.length()<8||!teacherId.substring(0,7).equals("teacher")){
                        throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                    }
                    teacherId = teacherId.replace("teacher","");
                } catch (JWTDecodeException j) {
                    throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                }
                teacher = loginService.findTeacherById(teacherId);
                if (teacher == null) {
                    throw new MyException(StatusCode.USER_NOT_EXIST,"用户不存在，请重新登录");
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(teacher.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                }
                return true;
            }
        }
        //检查有没有需要学员权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
//            System.out.println("检查有没有需要用户权限的注解");
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new MyException(StatusCode.USER_NOT_EXIST, "无token，请重新登录");
                }
                // 获取 token 中的 user id
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                    System.out.println(userId);
                    if(userId.length()<8&&!userId.substring(0,7).equals("student")){
                        throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                    }
                    userId = userId.replace("student","");
                } catch (JWTDecodeException j) {
                    throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                }
                user = loginService.findUserById(userId);
                if (user == null) {
                    throw new MyException(StatusCode.USER_NOT_EXIST,"用户不存在，请重新登录");
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                }
                return true;
            }
        }
        //检查有没有需要管理员权限的注解
        if (method.isAnnotationPresent(AdminLoginToken.class)) {
//            System.out.println("检查有没有需要用户权限的注解");
            AdminLoginToken adminLoginToken = method.getAnnotation(AdminLoginToken.class);
            if (adminLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new MyException(StatusCode.USER_NOT_EXIST, "无token，请重新登录");
                }
                // 获取 token 中的 user id
                String adminId;
                try {
                    adminId = JWT.decode(token).getAudience().get(0);
                    if(!adminId.substring(0,5).equals("admin")){
                        throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                    }
                    adminId = adminId.replace("admin","");
                } catch (JWTDecodeException j) {
                    throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                }
                admin = loginService.findAdminById(adminId);
                if (admin == null) {
                    throw new MyException(StatusCode.USER_NOT_EXIST,"用户不存在，请重新登录");
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
//                    System.out.println(token);
                } catch (JWTVerificationException e) {
                    throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                }
                return true;
            }
        }
        //检查有没有超级管理员的权限的注解
        if (method.isAnnotationPresent(SuperAuthority.class)) {
            System.out.println("检查有没有管理员的权限的注解");
            SuperAuthority superAuthority = method.getAnnotation(SuperAuthority.class);
            if (superAuthority.required()) {
                // 执行认证
                if (token == null) {
                    throw new MyException(StatusCode.USER_NOT_EXIST, "无token，请重新登录");
                }
                // 获取 token 中的 user id
                String adminId;
                try {
                    adminId = JWT.decode(token).getAudience().get(0);
                    if(!adminId.substring(0,5).equals("admin")){
                        throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                    }
                    adminId = adminId.replace("admin","");
                } catch (JWTDecodeException j) {
                    throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                }
                admin = loginService.findAdminById(adminId);
                if (admin == null) {
                    throw new MyException(StatusCode.USER_NOT_EXIST,"用户不存在，请重新登录");
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                    System.out.println(token);
                } catch (JWTVerificationException e) {
                    throw new MyException(StatusCode.NEED_LOGIN, "身份验证失败，请重新登录！");
                }
                if(admin.getAuthority() != 1){
                    throw new MyException(StatusCode.RETURN_ERROR, "权限不足！");
                }else{
                    return true;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
